package cn.jekun.shop.web.action;

import java.io.IOException;




import java.sql.Types;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.Constants.MAINFRAME_TYPE;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpTxnSeq;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpTxnSeqService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.pay.base.BasePay;
import cn.jekun.component.pay.common.utils.PayUtils;
import cn.jekun.component.pay.common.utils.WebPayTools;
import cn.jekun.component.pay.unionpay.tools.QuickPayConf;
import cn.jekun.component.shop.service.OrderService;
import cn.jekun.component.shop.service.ThirdBusinessService;
import cn.jekun.shop.common.service.ShopBaseAction;
import cn.jekun.shop.web.service.TransactionService;
import cn.jekun.shop.web.service.UnionPayService;

/**
 * 第三方支付
 * 
 * @author twj
 * 
 */
@SuppressWarnings("serial")
public class TransactionAction extends ShopBaseAction {
	
	//记录日志信息
	private static Logger logger=Logger.getLogger(TransactionAction.class);
		
	@Resource(name = TransactionService.BEAN_NAME)
	TransactionService transactionService;

	@Resource(name = UnionPayService.BEAN_NAME)
	UnionPayService unionPayService;
	
	@Resource(name=OrderService.BEAN_NAME)
	OrderService orderService;
	
	@Resource(name=ErpOrdersService.BEAN_NAME)
	ErpOrdersService orpOrdersService;
	
	@Resource(name=ErpTxnSeqService.BEAN_NAME)
	ErpTxnSeqService erpTxnSeqService;
	
	@Resource(name=ThirdBusinessService.BEAN_NAME)
	ThirdBusinessService thirdBusinessService;
	
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	
	@Resource(name=cn.jekun.shop.common.service.OrderService.BEAN_NAME)
	cn.jekun.shop.common.service.OrderService OrderService1;
	
	private String orderAmount;
	private String erroMessage;
	private String userId;
	private String loginSign;
	
	

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getLoginSign() {
		return loginSign;
	}

	public void setLoginSign(String loginSign) {
		this.loginSign = loginSign;
	}

	public String getOrderAmount() {
		return orderAmount;
	}

	public void setOrderAmount(String orderAmount) {
		this.orderAmount = orderAmount;
	}

	public String getErroMessage() {
		return erroMessage;
	}

	public void setErroMessage(String erroMessage) {
		this.erroMessage = erroMessage;
	}

	
	/**
	 * 重组第三方支付所需参数
	 */
	public String reconstructParams() {
		JSONObject jsonObject = new JSONObject();

		try {
			String payType = this.request.getParameter("payType");
			String mobile=null;
			String userId=null;
			// 验证是否登录
			if(payType!=null && payType.equals(Constants.ONLINE_PAYMENT.ALIPAY_WAP)){
				mobile = this.request.getParameter("mobile");
				userId= this.request.getParameter("userId");
				
				if(StringUtils.isBlank(mobile)){
					
					RsUser rsUser=this.rsUserService.one(userId);
					
					mobile=rsUser.getMobile();
				}
			}else{
				if (!isLogin()) {
					return timeout();
				}
				mobile = this.getSessionUser().getMobile();
				userId=this.getSessionUser().getUserId();
			}
			//支付
			String orderId = this.request.getParameter("order");
			String orderAmount = this.request.getParameter("orderAmount");
			String clientIp = this.request.getRemoteHost();// 客户端IP
			
    		String couponId=request.getParameter("couponId");//优惠券代码
    		String balance=request.getParameter("balance");//余额支付
    		String password=request.getParameter("password");//支付密码
    		
//    		String wxcode = request.getParameter("code");//h5微信公众号支付
    		try{
    			Map formTxnMap = new HashMap();
        		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
        		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
        		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
        		
	    		boolean isOk = this.orderService.otherPay(couponId, balance, this.getSessionUser().getUserId(), orderAmount, erpOrder, Constants.ONLINE_PAYMENT.UNION_PAY, "", "",password);//TODO
	    		if (isOk) {//支付成功
	                jsonObject.put("orderId", orderId);
	    			jsonObject.put("code", "1");
	    			jsonObject.put("payed", "1");//已经支付完成，不需要再支付
	    			jsonObject.put("message", "支付成功");
	    			return this.writeJson(jsonObject);
				}
    		}catch(BusinessException e){
                jsonObject.put("orderId", orderId);
    			jsonObject.put("code", "0");
    			jsonObject.put("payed", "0");//支付失败
    			jsonObject.put("message", e.getMessage());
    			
    			return this.writeJson(jsonObject);
    		}
    		
			
//			jsonObject = transactionService.reconstructParams(orderId, clientIp,
//					userId, mobile, payType,orderAmount,wxcode);
			jsonObject = transactionService.reconstructParams(orderId, clientIp,
					userId, mobile, payType,orderAmount);
			
			
		} catch (BusinessException e) {
			// TODO: handle exception
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage

			()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}

	
	/**
	 * 中国银联支付后台通知
	 * @return
	 */
	public void backNotify(){
		String[] resArr = new String[QuickPayConf.notifyVo.length]; 
		for(int i=0;i<QuickPayConf.notifyVo.length;i++){
			resArr[i] = request.getParameter(QuickPayConf.notifyVo[i]);
		}
		logger.info("##########################银联web支付后台通知报文："+resArr.toString());
		String signature = request.getParameter(QuickPayConf.signature);
		String signMethod = request.getParameter(QuickPayConf.signMethod);
		String orderId = request.getParameter("orderNumber");
		String transType = request.getParameter("transType");
		try {
			this.response.getOutputStream().print(HttpServletResponse.SC_OK);
			if("00".equals(resArr[10]) && "01".equals(transType)){
				transactionService.backNotify(resArr, signature, signMethod, orderId, "system",transType);
			}
			//交易为退货时
			else if("00".equals(resArr[10]) && "04".equals(transType) ){
				
				
			}
			//交易为撤销时
			else if("00".equals(resArr[10]) && "31".equals(transType)) {
				
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 中国银联支付前台通知
	 * 
	 * @return
	 */
	public String frontNotify() {
		JSONObject jsonObject = null;
		String returnResult = "";
		String[] resArr = new String[QuickPayConf.notifyVo.length]; 
		for(int i=0;i<QuickPayConf.notifyVo.length;i++){
			resArr[i] = request.getParameter(QuickPayConf.notifyVo[i]);
			System.out.println(QuickPayConf.notifyVo[i]+"="+resArr[i]); 
		}
		logger.info("##########################银联web支付前台通知报文："+resArr.toString());
		String signature = request.getParameter(QuickPayConf.signature);
		System.out.println("=====signature="+signature);
		String signMethod = request.getParameter(QuickPayConf.signMethod);
		System.out.println("=====signMethod="+signMethod);
		String orderId = request.getParameter("orderNumber");
		System.out.println("=====orderNumber="+orderId);
		String transType = request.getParameter("transType");//交易类型(01:消费交易  04：退货  31：消费撤销)
		System.out.println("=====transType="+transType);
		System.out.println("=====respCode"+resArr[10]); 
		//当交易为消费时
		try {
			if ("00".equals(resArr[10]) && "01".equals(transType)) {
				System.out.println(resArr[10] + "=======" + transType);
				jsonObject = transactionService.frontNotify(resArr, signature,
						signMethod, orderId, "system", transType);
				System.out.println("======" + jsonObject.toString());
				if (jsonObject.get("code").toString().equals("1")) {
					System.out.println("返回支付成功页面！");
					orderAmount = jsonObject.getString("orderAmount")
							.toString();
					orderAmount = WebPayTools.fenToYuan(orderAmount);
					returnResult = "/v1/pages/order/pay_success.jsp?orderAmount="
							+ orderAmount;
				} else {
					System.out.println("返回支付失败页面！");
					erroMessage = jsonObject.getString("message").toString();
					returnResult = "/v1/pages/order/pay_fail.jsp";
				}
			}
			// 交易为退货时
			else if ("00".equals(resArr[10]) && "04".equals(transType)) {

				returnResult = this.writeJson(jsonObject);
			}
			// 交易为撤销时
			else if ("00".equals(resArr[10]) && "31".equals(transType)) {

				returnResult = this.writeJson(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("returnResult:"+returnResult);
		return returnResult;
	}
	
	/**
	 * alipay前台通知（web版）
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String frontNotifyByAlipayWeb(){

		logger.info("********************TransactionAction frontNotifyByAlipayWeb Begin********************");
		JSONObject jsonObject = new JSONObject();
		String userId = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		BasePay alipayweb =  BasePay.CreateNewWebPay("07", "", "");
		alipayweb.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipayweb.NotifyFrontInfo();

		String code = jsonObject.getString("code");
		String message = jsonObject.getString("message");
		String returnResult = "";
		//alipay返回信息验证成功与否
		if (code.equals("1")) {
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String trade_status = jsonObject.getString("trade_status");// 交易状态
			String trade_no = jsonObject.getString("trade_no");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			// 原始交易为订单支付
			if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)//WAIT_BUYER_PAY 交易创建
					||trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)//TRADE_FINISHED 交易成功
					) {
				if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)) {
					logger.info("支付宝交易创建"+params.toString());
				}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)){
					logger.info("支付宝交易成功"+params.toString());
				}
				try {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Expires", "0");
					response.setHeader("Pragma", "No-cache");
					
					response.setContentType("text/html;charset=UTF-8");
					
					response.getWriter().write("success");
					response.getWriter().flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_SUCCESS)) {//TRADE_SUCCESS 支付成功
				logger.info("支付宝支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.ALIPAY,
							Constants.MAINFRAME_TYPE.FRONT_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_WEB);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************TransactionAction frontNotifyByAlipayWeb alipayweb支付后同步通知，订单状态已更新，不处理********************");
				} else {
					//第三方支付成功前台通知
						orderService.payRequestConfirmOrder(userId, orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.ALIPAY,
								Constants.MAINFRAME_TYPE.FRONT_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_WEB);
						
				}
				orderAmount = jsonObject.getString("total_fee")
						.toString();
				returnResult = "/v1/pages/order/pay_success.jsp?orderAmount="
						+ orderAmount;
			}
		} else {
			logger.info("********************TransactionAction frontNotifyByAlipayWeb alipayweb支付后同步通知消息处理失败，"
					+ message + "********************");
			erroMessage = jsonObject.getString("message").toString();
			returnResult = "/v1/pages/order/pay_fail.jsp";
		}
		return returnResult;
	}
	
	/**
	 * alipay后台通知（web版）
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String backNotifyByAlipayWeb(){
		logger.info("********************TransactionAction backNotifyByAlipayWeb Begin********************");
		JSONObject jsonObject = new JSONObject();
		String userId = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		BasePay alipayweb =  BasePay.CreateNewWebPay("07", "", "");
		alipayweb.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipayweb.NotifyBackInfo();

		String code = jsonObject.getString("code");
		String message = jsonObject.getString("message");
		
		//alipay返回信息验证成功与否
		if (code.equals("1")) {
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String trade_status = jsonObject.getString("trade_status");// 交易状态
			String trade_no = jsonObject.getString("trade_no");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			// 原始交易为订单支付
			if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)//WAIT_BUYER_PAY 交易创建
					||trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)//TRADE_FINISHED 交易成功
					) {
				if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)) {
					logger.info("支付宝交易创建"+params.toString());
				}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)){
					logger.info("支付宝交易成功"+params.toString());
				}
				try {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Expires", "0");
					response.setHeader("Pragma", "No-cache");
					
					response.setContentType("text/html;charset=UTF-8");
					
					response.getWriter().write("success");
					response.getWriter().flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_SUCCESS)) {//TRADE_SUCCESS 支付成功
				logger.info("支付宝支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
						
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.ALIPAY,
							Constants.MAINFRAME_TYPE.BACK_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_WEB);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************TransactionAction backNotifyByAlipayWeb alipayweb支付后台通知，订单状态已更新，不处理********************");
				} else {
					try {
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Expires", "0");
						response.setHeader("Pragma", "No-cache");
						
						response.setContentType("text/html;charset=UTF-8");
						
						response.getWriter().write("success");
						response.getWriter().flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//第三方支付成功后台通知
						orderService.payConfirmOrder(userId, orderID,Constants.ONLINE_PAYMENT.ALIPAY, trade_no,Constants.PAY_CHANNEL.PAY_IOS);// 保存银联返回的订单支付号，后续退货及撤消需要用到
						thirdBusinessService.callThirdService(orderID, userId);
						// 支付成功后推送
						OrderService1.pushOrderByPayNo(orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.ALIPAY,
								Constants.MAINFRAME_TYPE.BACK_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_WEB);
				}
			}
		} else {
			logger.info("********************TransactionAction backNotifyByAlipayWeb alipayweb支付异步通知消息处理失败，"
					+ message + "********************");
		}
		return null;
	}
	
	
	
	/**
	 * alipay前台通知（wap版）
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String frontNotifyByAlipayWap(){

		logger.info("********************TransactionAction frontNotifyByAlipayWap Begin********************");
		JSONObject jsonObject = new JSONObject();
		String system = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		BasePay alipaywap =  BasePay.CreateNewWebPay("08", "", "");
		alipaywap.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipaywap.NotifyFrontInfo();
		String code = jsonObject.getString("code");
		String message = jsonObject.getString("message");
		String returnResult = "";
		//alipay返回信息验证成功与否
		if (code.equals("1")) {
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String trade_status = jsonObject.getString("result");// 交易状态
			String trade_no = jsonObject.getString("trade_no");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			
			// 原始交易为订单支付
			if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)//WAIT_BUYER_PAY 交易创建
					||trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)//TRADE_FINISHED 交易成功
					) {
				if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)) {
					logger.info("支付宝交易创建"+params.toString());
				}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)){
					logger.info("支付宝交易成功"+params.toString());
				}
			}else if (trade_status.equals("success")) {//TRADE_SUCCESS 支付成功
				logger.info("支付宝支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.ALIPAY,
							Constants.MAINFRAME_TYPE.FRONT_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_WAP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************TransactionAction frontNotifyByAlipaywap alipaywap支付后同步通知，订单状态已更新，不处理********************");
				} else {
					//第三方支付成功前台通知
						orderService.payRequestConfirmOrder(system, orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.ALIPAY,
								Constants.MAINFRAME_TYPE.FRONT_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_WAP);
						
				}
				RsUser uses=this.rsUserService.one(orders.getUserId());
				userId=uses.getUserId();
				loginSign=uses.getLoginSignApp();
				returnResult = "/v1/h5/pages/pay_success/"+uses.getUserId()+"/"+uses.getLoginSignApp()+".html";
			}
		} else {
			logger.info("********************TransactionAction frontNotifyByAlipaywap alipaywap支付后同步通知消息处理失败，"
					+ message + "********************");
			erroMessage = jsonObject.getString("message").toString();
			returnResult = "/v1/h5/pages/pay_fail.jsp";
		}
		logger.info("********************通知页面URL："+ returnResult + "********************");
		
		return returnResult;
	}
	
	/**
	 * alipay后台通知（Wap版）
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String backNotifyByAlipayWap(){
		logger.info("********************TransactionAction backNotifyByAlipayWap Begin********************");
		JSONObject jsonObject = new JSONObject();
		String userId = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		BasePay alipaywap =  BasePay.CreateNewWebPay("08", "", "");
		alipaywap.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipaywap.NotifyBackInfo();

		String code = jsonObject.getString("code");
		String message = jsonObject.getString("message");
		
		//alipay返回信息验证成功与否
		if (code.equals("1")) {
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String trade_status = jsonObject.getString("trade_status");// 交易状态
			String trade_no = jsonObject.getString("trade_no");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			// 原始交易为订单支付
			if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)//WAIT_BUYER_PAY 交易创建
					||trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)//TRADE_FINISHED 交易成功
					) {
				if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)) {
					logger.info("支付宝交易创建"+params.toString());
				}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)){
					logger.info("支付宝交易成功"+params.toString());
				}
				try {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Expires", "0");
					response.setHeader("Pragma", "No-cache");
					
					response.setContentType("text/html;charset=UTF-8");
					
					response.getWriter().write("success");
					response.getWriter().flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_SUCCESS)) {//TRADE_SUCCESS 支付成功
				logger.info("支付宝支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
						
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.ALIPAY,
							Constants.MAINFRAME_TYPE.BACK_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_WAP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************TransactionAction backNotifyByAlipaywap alipaywap支付后台通知，订单状态已更新，不处理********************");
				} else {
					try {
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Expires", "0");
						response.setHeader("Pragma", "No-cache");
						
						response.setContentType("text/html;charset=UTF-8");
						
						response.getWriter().write("success");
						response.getWriter().flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//第三方支付成功后台通知
						orderService.payConfirmOrder(userId, orderID,Constants.ONLINE_PAYMENT.ALIPAY, trade_no,Constants.PAY_CHANNEL.PAY_WAP);// 保存银联返回的订单支付号，后续退货及撤消需要用到
						thirdBusinessService.callThirdService(orderID, userId);
						// 支付成功后推送
						OrderService1.pushOrderByPayNo(orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.ALIPAY,
								Constants.MAINFRAME_TYPE.BACK_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_WAP);
				}
			}
		} else {
			logger.info("********************TransactionAction backNotifyByAlipaywap alipaywap支付异步通知消息处理失败，"
					+ message + "********************");
		}
		return null;
	}
	
	/**
	 * alipay操作中断（Wap版）
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String merchantByAlipayWap(){
		logger.info("********************TransactionAction alipaywap操作中断 ********************");
		return "/v1/pages/order/pay_fail.jsp";
	}
}
